const { throttle, debounce } = require("./template.js")

function testThrottleDebounce() {
  console.log("=== 节流防抖测试 ===")

  // 测试节流函数
  console.log(
    "1. 节流函数基本功能:",
    (() => {
      let count = 0
      const throttledFn = throttle(() => {
        count++
      }, 100)

      // 快速调用多次
      throttledFn()
      throttledFn()
      throttledFn()

      // 在100ms内应该只执行一次
      return count === 1
    })()
  )

  console.log(
    "2. 节流函数时间间隔:",
    (() => {
      let count = 0
      const throttledFn = throttle(() => {
        count++
      }, 200)

      throttledFn() // 第一次调用

      // 立即检查第一次调用
      if (count !== 1) return false

      // 模拟时间流逝后再次调用
      throttledFn() // 第二次调用

      // 应该执行两次
      return count === 2
    })()
  )

  // 测试防抖函数
  console.log(
    "3. 防抖函数基本功能:",
    (() => {
      let count = 0
      const debouncedFn = debounce(() => {
        count++
      }, 100)

      // 快速调用多次
      debouncedFn()
      debouncedFn()
      debouncedFn()

      // 立即检查，防抖函数不应该立即执行
      return count === 0
    })()
  )

  console.log(
    "4. 防抖函数延迟执行:",
    (() => {
      let result = ""
      const debouncedFn = debounce((msg) => {
        result = msg
      }, 50)

      debouncedFn("first")
      debouncedFn("second")
      debouncedFn("third")

      // 立即检查，防抖函数不应该立即执行
      return result === ""
    })()
  )

  console.log(
    "5. 节流函数参数传递:",
    (() => {
      let lastArgs = null
      const throttledFn = throttle((a, b) => {
        lastArgs = [a, b]
      }, 100)

      throttledFn("hello", "world")
      throttledFn("foo", "bar")

      return lastArgs && lastArgs[0] === "hello" && lastArgs[1] === "world"
    })()
  )

  console.log(
    "6. 防抖函数this绑定:",
    (() => {
      const obj = {
        value: 0,
        increment: debounce(function () {
          this.value++
        }, 50)
      }

      obj.increment()
      obj.increment()
      obj.increment()

      // 立即检查，防抖函数不应该立即执行
      return obj.value === 0
    })()
  )

  console.log(
    "7. 节流函数返回值:",
    (() => {
      const throttledFn = throttle(() => {
        return "throttled"
      }, 100)

      const result1 = throttledFn()
      const result2 = throttledFn()

      return result1 === "throttled" && result2 === undefined
    })()
  )

  console.log(
    "8. 防抖函数取消功能:",
    (() => {
      let count = 0
      const debouncedFn = debounce(() => {
        count++
      }, 100)

      debouncedFn()
      if (typeof debouncedFn.cancel === "function") {
        debouncedFn.cancel() // 取消之前的调用
      }
      debouncedFn()

      // 立即检查，防抖函数不应该立即执行
      return count === 0
    })()
  )
}

testThrottleDebounce()
